<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */

    /*********************************************************
    *            --== InArch ==--
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @copyright essentialmind.com 2005
    *
    *********************************************************/
    
    /***
    * Class clientNodePage
    ****
    * This classs represents a root page of any solution
    ****
    * @package clientNodes
    * @author A Kulikov <a.kulikov@gmail.com>
    * @version n/a
    * @copyright essentialmind.com 2005
    ***/
    class clientNodeShopCart extends clientNode{

        /**
         * Process inputs
         * 
         * @return void 
         **/
        public function process(){
            $data = $this->db->getRow("SELECT * FROM node_shop_cart WHERE id = ".$this->object);
            $data['title'] = $this->db->getOne("SELECT title FROM pagemap WHERE id = ".$this->reference);
            
            //what step? -- breadcrumbs
            if($_GET['step'] == 2){
                $item = $this->crumbs->pop();
                $this->crumbs->push($item['title'],$item['url']);                
                $this->crumbs->push('Step 2 &mdash; delivery',$item['url'].'?step=2');                                
                
                //figure out children maaaan
                $kids = 0;
                foreach($_SESSION['CART']->items as $aid => $ticket){
                    if($ticket->quant2() > $kids){
                        $kids = $ticket->quant2();
                    }
                }
                $this->smarty->assign('kids',$kids);
                
            }elseif($_GET['step'] == 3){
                $item = $this->crumbs->pop();
                $this->crumbs->push($item['title'],$item['url']);                
                $this->crumbs->push('Step 2 &mdash; delivery',$item['url'].'?step=2');              
                $this->crumbs->push('Step 3 &mdash; check &amp; order',$item['url'].'?step=3'); 
            }elseif($_GET['step'] == 'mpay' or $_GET['step'] == 'pay' or $_GET['STEP'] == 'pay'){
                $item = $this->crumbs->pop();
            }elseif($_GET['step'] == 4){
                $this->crumbs->push('Order Created',null);              
            }
            
            
                        
            //check POST
            if($_POST['addArticle']){
                
                if(!$_SESSION['CART'] or ($_SESSION['CART'] and !is_object($_SESSION['CART']))){
                    $_SESSION['CART'] = new shoppingCart($this->db);
                }                    
                $_SESSION['CART']->addItem((int)$_REQUEST['articleId'],(int)$_REQUEST['q1'],(int)$_REQUEST['q2']);                
                
            }elseif($_POST['checkout']){
                header('Location: ?step=2');
                exit;
            }elseif($_POST['step2']){
                //error check
                $errors = array();
                
                if(empty($_POST['ticketOwnerName'])){
                    $errors['ticketOwnerName'] = true;
                }
                
                if(!eregi("^[A-Za-z0-9_\.\-]+@[A-Za-z0-9_\.\-]+\.[A-Za-z0-9_\-][A-Za-z0-9_\-]+$", $_POST['ticketOwnerMail'])){
                    $errors['ticketOwnerMail'] = true;
                }
                
                if(isset($_POST['kid_age'])){
                    foreach($_POST['kid_age'] as $kid){
                      if(empty($kid)){
                        $errors['kidError'] = true;
                        break;
                      }
                    }
                }
                
                
                //any errors?
                if(empty($errors)){
                    if($_POST['ticket_date_Day'] < 10){
                        $_POST['ticket_date_Day'] = '0'.$_POST['ticket_date_Day'];
                    }
                    
                    //save info in session and go on
                    $_SESSION['order']['term'] = $_POST['ticket_date_Year'].'-'.$_POST['ticket_date_Month'].'-'.$_POST['ticket_date_Day'];
                    $_SESSION['order']['name'] = $_POST['ticketOwnerName'];
                    $_SESSION['order']['tel']  = $_POST['ticketOwnerPhone'];
                    $_SESSION['order']['mail'] = $_POST['ticketOwnerMail'];
                    $_SESSION['order']['kids'] = implode(',',(array)$_POST['kid_age']);
                    header('Location: '.$item['url'].'?step=3');
                    exit;
                }else{
                    $this->smarty->assign('errors',$errors);
                }
            }elseif($_POST['step3']){
                $this->log->recordAction("Creating New Order");
        
                #######                
                //start transaction
                $this->db->StartTrans();
                
                //create order
                $this->db->Execute("INSERT INTO node_shop_order(name,tel,mail,term,price,info) 
                                                            VALUES(
                                                                    ".$this->db->qstr($_SESSION['order']['name']).",
                                                                    ".$this->db->qstr($_SESSION['order']['tel']) .",
                                                                    ".$this->db->qstr($_SESSION['order']['mail']).",
                                                                    ".$this->db->qstr($_SESSION['order']['term']).",
                                                                    ".$_SESSION['CART']->price().",
                                                                    ".$this->db->qstr($_SESSION['order']['kids'])."
                                                                )");
                $orderID = $this->db->getOne("SELECT last_value FROM node_shop_order_id_seq");
                
                $discount = $_SESSION['CART']->discount();            
            
                foreach($_SESSION['CART']->items as $aid => $ticket){
                    $this->db->Execute("INSERT INTO node_shop_order_article(article_id,order_id,quant1,quant2,price,price_kids,tax)
                                                            VALUES(
                                                                    ".(int)$aid.",
                                                                    ".(int)$orderID.",
                                                                    ".$ticket->quant().",
                                                                    ".$ticket->quant2().",
                                                                    ".(float)($ticket->price1()*(1 + $discount / 100)).",
                                                                    ".(float)($ticket->price2()*(1 + $discount / 100)).",
                                                                    ".(float)$ticket->get('tax')."
                                                                )");
                }
                
                //end transaction
                $this->db->CompleteTrans();
                #######
                
                //log action
                $this->log->recordAction("Successfully created Order -- \"".$orderID."\"");
                                                        
                //redirect
                header('Location: '.$item['url'].'?step=mpay&orderid='.$orderID);  //first go to the payment processor
                exit;
            }elseif($_GET['step'] == 'mpay'){
                
                if($_SESSION['admin']){
                   unset($_SESSION['order']);
                   unset($_SESSION['CART']);
                  
                   header('Location: '.$item['url'].'?STEP=pay&KEY=bluebell2005&TID='.$_GET['orderid'].'&MPAYTID='.uniqid('MP').'&STATUS=test&PRICE=0&CURRENCY=EUR&P_TYPE=voucher&BRAND=test&SHIPPING_ART=test&BILLING_ADR=test&ORDERDESC=Vouchers&CUSTOMER=VHADMIN');
                   exit;
                }
                
                $discount = $_SESSION['CART']->discount();
                
                $this->log->recordAction("Calling the Merchant Processor");
                ## call the payment processor
                include_once(ROOT."mpay24/SelectPayment.php");
                
                $etp_url = "https://www.mPAY24.com/bin/secure/at/etpv5";
    
                $request       = new SelectPayment($etp_url);
                $billing_addr  = new Address();
                $shipping_addr = new Address();
		        $style         = new Style();
                
                
                // Set all Attributes
                $request->setMerchantId("71140");
                //$request->setIpAddress('');
                //$request->setCssName("stylesheet_71140");
                $request->setLanguage("DE");
                $request->setTemplateSet("WEB");
                $request->setDescription("ViennaHighlights.com Payment");
                $request->setTid($_GET['orderid']);
                //$request->setTotalShippingCosts(0);
                $request->addTax('10,'.number_format($_SESSION['CART']->price()*0.1,2));
                $request->setTotalPrice(number_format($_SESSION['CART']->price(),2));
                $request->setCurrency("EUR");
             
                // Set PaymentTypes that should be offered to customer
                //$request->addPaymentType("CC,AMEX");
                $request->addPaymentType("CC");
                //$request->addPaymentType("CC,DINERS");
                //$request->addPaymentType("CC,MASTERCARD");
                //$request->addPaymentType("EPS,BAWAG");
                //$request->addPaymentType("PB");
                                                
                
                // set Item1
                $counter = 1;
                foreach($_SESSION['CART']->items as $aid => $ticket){
                    
                    
                    //now, do we have ADULT AND CHILD tickets?
                    if($ticket->quant() > 0){
                        $item_1 = new Item();
                        $item_1->setNumber($counter);
                        $item_1->setProductNr($aid);
                        $item_1->setDescription(str_replace('&ouml;','oe',$ticket->get('name')).' / Adults');
                        $item_1->setQuantity($ticket->quant());
                        $item_1->setItemPrice(number_format($ticket->price1()*(1 + $discount / 100)*0.9,2));
                        $item_1->setPrice(number_format($ticket->price1()*$ticket->quant()*(1 + $discount / 100)*0.9,2));
                        $item_1->setPackage("PDF Voucher");
                        $request->addItem($item_1);
                        $counter++;
                    }
                    
                    if($ticket->quant2() > 0){
                        $item_1 = new Item();
                        $item_1->setNumber($counter);
                        $item_1->setProductNr($aid);
                        $item_1->setDescription(str_replace('&ouml;','oe',$ticket->get('name')).' / Children');
                        $item_1->setQuantity($ticket->quant2());
                        $item_1->setItemPrice(number_format($ticket->price2()*(1 + $discount / 100)*0.9,2));
                        $item_1->setPrice(number_format($ticket->price2()*$ticket->quant2()*(1 + $discount / 100)*0.9,2));
                        $item_1->setPackage("PDF Voucher");
                        $request->addItem($item_1);
                        $counter++;
                    }                                        
                }
                
                // set BillingAddress
                //$billing_addr->setTitle(" ");
                $billing_addr->setFirstName(" ");
                $billing_addr->setLastName(" ");
                $billing_addr->setStreet(" ");
                $billing_addr->setZip(" ");
                $billing_addr->setCity(" ");
                $billing_addr->setCountry(" ");
                //$billing_addr->setPhone($_SESSION['order']['tel']);
                //$billing_addr->setFax(" ");
                $billing_addr->setEmail($_SESSION['order']['mail']);
                $request->setBillingAddress($billing_addr);
                
                // set ShippingAddress
                //$shipping_addr->setTitle(" ");
                //$shipping_addr->setFirstName(" ");
                //$shipping_addr->setLastName(" ");
                //$shipping_addr->setStreet(" ");
                //$shipping_addr->setZip(" ");
                //$shipping_addr->setCity(" ");
                //$shipping_addr->setCountry(" ");
                //$shipping_addr->setPhone($_SESSION['order']['tel']);
                //$shipping_addr->setFax(" ");
                //$shipping_addr->setEmail($_SESSION['order']['mail']);
                //$request->setShippingAddress($shipping_addr);
                
                $style->setLogoStyle("");
                $style->setPageHeaderStyle("");
                $style->setPageCaptionStyle("");
                $style->setPageStyle("");
                $style->setSCStyle("");
                $style->setSCHeader("");
                $style->setSCHeaderStyle("");
                $style->setSCCaptionStyle("");
                $style->setSCNumberStyle("");
                $style->setSCProductNrStyle("");
                $style->setSCDescriptionStyle("");
                $style->setSCPackageStyle("");
                $style->setSCQuantityStyle("");
                $style->setSCItemPriceStyle("");
                $style->setSCPriceStyle("");
                $style->setSCItemEvenStyle("");
                $style->setSCItemOddStyle("");
                $style->setShippingCostsHStyle("");
                $style->setShippingCostsStyle("");
                $style->setTaxHStyle("");
                $style->setTaxStyle("");
                $style->setPRHeader("");
                $style->setPRHeaderStyle("");
                $style->setPRStyle("");
                $request->setStyle($style);
                                                                                        
                // create XMLFILE
                $request->setXmlDir(ROOT."mpay24/xmlfiles");
                $request->createXmlFile();
                $request->saveXmlFile();
                //$request->getXmlFile();
                
                $request->send();
                $request->parseResponse();
                //echo $request->getResponse();
                //exit;
                ## /end call  
                //unset($_SESSION['order']);
                //unset($_SESSION['CART']);
                exit;
                
            }elseif($_GET['step'] == '4'){
                
                //empty cart
                unset($_SESSION['order']);
                unset($_SESSION['CART']);
                
                ## Order Created and Will Be Shipped Soon ##
                // ...
                ## Nothing here, really ##
                
            }elseif($_GET['step'] == 'error'){
                
                ## There was a payment error ##
                // ...
                ## Nothing here, really
                
            }elseif($_GET['STEP'] == 'pay' and $_GET['KEY'] == 'bluebell2005' and $_GET['TID']){
                
                ## The order was payed for, thus mark it so and EXIT
                $this->log->recordAction("Order ".$_GET['TID']." was payed for!");
                
                if($_GET['STATUS'] and $_GET['STATUS'] != 'ERROR'){
                    $payed = 'TRUE';
                }else{
                    $payed = 'FALSE';
                }

                //$this->db->debug=1;                
                $this->db->Execute("UPDATE node_shop_order SET 
                                         payed       = ".$payed.", 
                                         tid         = ".$this->db->qstr($_GET['MPAYTID']).",
                                         
                                         t_status    = ".$this->db->qstr($_GET['STATUS']).",
                                         t_intime    = NOW(),
                                         t_price     = ".$this->db->qstr((int)$_GET['PRICE']).",
                                         t_currency  = ".$this->db->qstr($_GET['CURRENCY']).",
                                         t_p_type    = ".$this->db->qstr($_GET['P_TYPE']).",
                                         t_brand     = ".$this->db->qstr($_GET['BRAND']).",
                                         t_ship_adr  = ".$this->db->qstr($_GET['SHIPPING_ADR']).",
                                         t_bill_adr  = ".$this->db->qstr($_GET['BILLING_ADR']).",
                                         t_orderdesc = ".$this->db->qstr($_GET['ORDERDESC']).",
                                         t_customer  = ".$this->db->qstr('cname')."
                                         
                                       WHERE id = ".(int)$_GET['TID']);
                
                if($_SESSION['admin']){
                    header("Location: ".$item['url']."?step=4&TID=".$_GET['TID']);
                    exit;
                }
                
                echo 'OK';
                exit;
            }
            
            
            
            //nothing
            $this->smarty->assign('data',$data);
        }
        

        /**
         * set the action template to page.html
         * 
         * @return void
         **/
        public function setTemplate(){
            $this->setActionTemplate('cart.html');
        }
    }
?>
